package com.lemon.smartsafetynew.ui.activity.hidden;

import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafetynew.ui.activity.base.SwipeBackActivity;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.FileUtil;
import com.lemon.smartsafety.utils.common.LemonFileHelper;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.lemon.smartsafetynew.entity.common.DateTypeEnum;
import com.lemon.smartsafetynew.entity.event.common.ViewEvent;
import com.lemon.smartsafetynew.entity.event.hidden.HiddenMediaNewEvent;
import com.lemon.smartsafetynew.entity.hidden.SafeHiddenBo;
import com.lemon.smartsafetynew.entity.hidden.SafeHiddenDangerFile;
import com.lemon.smartsafetynew.entity.hidden.SafeHiddenDownloadVo;
import com.lemon.smartsafetynew.entity.hidden.SafeHiddenProcessItemVo;
import com.lemon.smartsafetynew.net.services.SafeHiddenServices;
import com.lemon.smartsafetynew.ui.adapter.hidden.SafeHiddenAttachmentFileVoAdapter;
import com.lemon.smartsafetynew.util.common.CheckAppExist;
import com.lemon.smartsafetynew.util.common.CommonUtil;
import com.lemon.smartsafetynew.util.common.UrlFormatUtils;
import com.lemon.smartsafetynew.util.constants.KeyConstants;
import com.lemon.smartsafetynew.util.user.AccountUtil;
import com.lemon.smartsafetynew.util.user.UserTypeUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import okhttp3.Call;

/**
 * Created by Andrew on 2017/10/24.
 */

public class SafeHiddenProcessDetailActivity extends SwipeBackActivity {

    @Bind(R.id.hidden_one_label_tv)
    TextView hiddenOneLabelTv;
    @Bind(R.id.hidden_one_tv)
    TextView hiddenOneTv;
    @Bind(R.id.hidden_one_layout)
    LinearLayout hiddenOneLayout;

    @Bind(R.id.hidden_two_label_tv)
    TextView hiddenTwoLabelTv;
    @Bind(R.id.hidden_two_tv)
    TextView hiddenTwoTv;
    @Bind(R.id.hidden_two_layout)
    LinearLayout hiddenTwoLayout;

    @Bind(R.id.hidden_three_label_tv)
    TextView hiddenThreeLabelTv;
    @Bind(R.id.hidden_three_tv)
    TextView hiddenThreeTv;
    @Bind(R.id.hidden_three_layout)
    LinearLayout hiddenThreeLayout;

    @Bind(R.id.hidden_four_label_tv)
    TextView hiddenFourLabelTv;
    @Bind(R.id.hidden_four_tv)
    TextView hiddenFourTv;
    @Bind(R.id.hidden_four_layout)
    LinearLayout hiddenFourLayout;

    @Bind(R.id.hidden_five_label_tv)
    TextView hiddenFiveLabelTv;
    @Bind(R.id.hidden_five_tv)
    TextView hiddenFiveTv;
    @Bind(R.id.hidden_five_layout)
    LinearLayout hiddenFiveLayout;

    @Bind(R.id.label_one_tv)
    TextView labelOneTv;
    @Bind(R.id.name_one_tv)
    TextView nameOneTv;
    @Bind(R.id.layout_one)
    LinearLayout layoutOne;

    @Bind(R.id.label_two_tv)
    TextView labelTwoTv;
    @Bind(R.id.name_two_tv)
    TextView nameTwoTv;
    @Bind(R.id.layout_two)
    LinearLayout layoutTwo;

    @Bind(R.id.label_three_tv)
    TextView labelThreeTv;
    @Bind(R.id.name_three_tv)
    TextView nameThreeTv;
    @Bind(R.id.layout_three)
    LinearLayout layoutThree;

    @Bind(R.id.layout_four)
    LinearLayout layoutFour;

    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;

    @Bind(R.id.printer_btn)
    Button printerBtn;
    @Bind(R.id.upload_btn)
    Button uploadBtn;
    @Bind(R.id.view_line)
    View viewLine;
    @Bind(R.id.bottom_layout)
    LinearLayout bottomLayout;


    private static SafeHiddenProcessItemVo safeHiddenProcessItemVo;
    private static SafeHiddenDownloadVo safeHiddenDownloadVo;

    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {

            if (bundle.containsKey(KeyConstants.KEY_SAFE_HIDDEN_PROCESS_ITEM_VO)) {
                safeHiddenProcessItemVo = (SafeHiddenProcessItemVo) bundle.getSerializable(KeyConstants.KEY_SAFE_HIDDEN_PROCESS_ITEM_VO);
            }

            if(bundle.containsKey(KeyConstants.KEY_SAFE_HIDDEN_DOWNLOAD_VO)) {
                safeHiddenDownloadVo = (SafeHiddenDownloadVo) bundle.getSerializable(KeyConstants.KEY_SAFE_HIDDEN_DOWNLOAD_VO);
            }
        }
    }

    @Override
    protected void initTitle() {
        this.setBarTitle("处理流程");
    }

    @Override
    protected void callFinish() {
        AppService.getBus().post(new ViewEvent(SafeHiddenProcessDetailActivity.class.getName()));
        AppManager.getAppManager().finishActivity(SafeHiddenProcessDetailActivity.this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_safe_hidden_process_detail;
    }

    @Override
    protected void initViews() {
        super.initViews();

    }

    @Override
    protected void onResume() {
        super.onResume();

        initRecyclerView();
        initCommon();

    }

    private void initCommon() {
        if (SafeHiddenBo.Status.create.getValue().equals(safeHiddenProcessItemVo.getType())) {
            create();
        } else if (SafeHiddenBo.Status.rectify.getValue().equals(safeHiddenProcessItemVo.getType())) {
            rectify();
        } else if (SafeHiddenBo.Status.review.getValue().equals(safeHiddenProcessItemVo.getType())) {
            review();
        } else if (SafeHiddenBo.Status.doc.getValue().equals(safeHiddenProcessItemVo.getType())) {
            if (SafeHiddenBo.Doc.site_inspection_doc.getValue().equals(safeHiddenProcessItemVo.getDocument_type())) {
                /**
                 * 政府人员不需要持有证书，即可打印和上传的文书
                 */
                govWithoutCertificateDoc();
            } else {
                /**
                 * 即使是政府人员，但必须是有证书的人，才可以打印和上传的文书
                 */
                govWithCertificateDoc();
            }
        }
    }

    /**
     * 发起
     */
    private void create() {

        hiddenThreeLayout.setVisibility(View.VISIBLE);
        hiddenFourLayout.setVisibility(View.VISIBLE);
        hiddenFiveLayout.setVisibility(View.VISIBLE);
        layoutThree.setVisibility(View.VISIBLE);

        hiddenOneLabelTv.setText("隐患来源：");
        //hiddenOneTv.setText(SafeHiddenUtils.getSourceType(safeHiddenDownloadVo.getSource_type()));
        hiddenOneLayout.setVisibility(View.GONE);

        hiddenTwoLabelTv.setText("检查部位：");
        //hiddenTwoTv.setText(CommonUtil.avoidNullString(safeHiddenDownloadVo.getName()));
        hiddenTwoLayout.setVisibility(View.GONE);

        hiddenThreeLabelTv.setText("检查类型：");
        //hiddenThreeTv.setText(CommonUtil.avoidNullString(safeHiddenDownloadVo.getCheck_type_name()));
        hiddenThreeLayout.setVisibility(View.GONE);

        hiddenFourLabelTv.setText("检查时间：");
        //hiddenFourTv.setText(CommonUtil.secondToTimeStr(safeHiddenProcessItemVo.getCreate_time(), DateTypeEnum.DAY));
        hiddenFourLayout.setVisibility(View.GONE);

        hiddenFiveLabelTv.setText("检查人员：");
        hiddenFiveTv.setText(CommonUtil.avoidNullString(safeHiddenProcessItemVo.getOperator_name()));

        //labelOneTv.setText("隐患分类：");
        //nameOneTv.setText(CommonUtil.avoidNullString(safeHiddenDownloadVo.getClassify_name()));
        //layoutOne.setVisibility(View.GONE);

        labelOneTv.setText("检查时间：");
        nameOneTv.setText(CommonUtil.secondToTimeStr(safeHiddenProcessItemVo.getCreate_time(), DateTypeEnum.DAY));

        labelTwoTv.setText("隐患级别：");
        nameTwoTv.setText(CommonUtil.avoidNullString(safeHiddenDownloadVo.getLevel_name()));

        labelThreeTv.setText("隐患描述：");
        nameThreeTv.setText(CommonUtil.avoidNullString(safeHiddenDownloadVo.getDesc()));

        getAttachment(safeHiddenProcessItemVo.getId());
    }

    /**
     * 整改
     */
    private void rectify() {

        hiddenThreeLayout.setVisibility(View.VISIBLE);
        hiddenFourLayout.setVisibility(View.VISIBLE);
        hiddenFiveLayout.setVisibility(View.GONE);
        layoutThree.setVisibility(View.VISIBLE);


        hiddenOneLabelTv.setText("责任部门：");
        //hiddenOneTv.setText(CommonUtil.avoidNullString(safeHiddenDownloadVo.getRectify_dept()));
        hiddenOneLayout.setVisibility(View.GONE);

        hiddenTwoLabelTv.setText("整改人员：");
        hiddenTwoTv.setText(CommonUtil.avoidNullString(safeHiddenProcessItemVo.getOperator_name()));

        hiddenThreeLabelTv.setText("计划完成时间：");
        //hiddenThreeTv.setText(CommonUtil.secondToTimeStr(safeHiddenDownloadVo.getPlan_rectify_time(), DateTypeEnum.DAY));
        hiddenThreeLayout.setVisibility(View.GONE);

        hiddenFourLabelTv.setText("预计整改金额：");
        //hiddenFourTv.setText(CommonUtil.avoidNullString(safeHiddenDownloadVo.getPlan_rectify_money()));
        hiddenFourLayout.setVisibility(View.GONE);

        labelOneTv.setText("实际整改时间：");
        nameOneTv.setText(CommonUtil.secondToTimeStr(safeHiddenProcessItemVo.getCreate_time(), DateTypeEnum.DAY));

        labelTwoTv.setText("实际整改金额：");
        nameTwoTv.setText(CommonUtil.avoidNullString(safeHiddenProcessItemVo.getMoney()));

        labelThreeTv.setText("整改措施：");
        nameThreeTv.setText(CommonUtil.avoidNullString(safeHiddenProcessItemVo.getOperate_content()));

        getAttachment(safeHiddenProcessItemVo.getId());
    }

    /**
     * 复查
     */
    private void review() {

        hiddenThreeLayout.setVisibility(View.GONE);
        hiddenFourLayout.setVisibility(View.GONE);
        hiddenFiveLayout.setVisibility(View.GONE);
        layoutThree.setVisibility(View.GONE);

        hiddenOneLabelTv.setText("复查部门：");
        //hiddenOneTv.setText(CommonUtil.avoidNullString(safeHiddenDownloadVo.getReview_dept()));
        hiddenOneLayout.setVisibility(View.GONE);

        hiddenTwoLabelTv.setText("复查人员：");
        hiddenTwoTv.setText(CommonUtil.avoidNullString(safeHiddenProcessItemVo.getOperator_name()));

        labelOneTv.setText("复查时间：");
        nameOneTv.setText(CommonUtil.secondToTimeStr(safeHiddenProcessItemVo.getCreate_time(), DateTypeEnum.DAY));

        labelTwoTv.setText("备注说明：");
        nameTwoTv.setText(CommonUtil.avoidNullString(safeHiddenProcessItemVo.getRemark()));

        getAttachment(safeHiddenProcessItemVo.getId());

    }

    /**
     * 不需要持证的政府人员 才能打印和上传的文书
     */
    private void govWithoutCertificateDoc() {

        hiddenTwoLayout.setVisibility(View.GONE);
        hiddenThreeLayout.setVisibility(View.GONE);
        hiddenFourLayout.setVisibility(View.GONE);
        hiddenFiveLayout.setVisibility(View.GONE);
        layoutTwo.setVisibility(View.GONE);
        layoutThree.setVisibility(View.GONE);
        layoutFour.setVisibility(View.VISIBLE);

        hiddenOneLabelTv.setText("开具文书人员：");
        hiddenOneTv.setText(CommonUtil.avoidNullString(safeHiddenProcessItemVo.getOperator_name()));

        labelOneTv.setText("开具时间：");
        nameOneTv.setText(CommonUtil.timeToStr(safeHiddenProcessItemVo.getCreate_time()));

        getAttachment(safeHiddenProcessItemVo.getId());
    }


    /**
     * 需要持证的政府人员 才能打印和上传的文书
     */
    private void govWithCertificateDoc() {

        hiddenTwoLayout.setVisibility(View.GONE);
        hiddenThreeLayout.setVisibility(View.GONE);
        hiddenFourLayout.setVisibility(View.GONE);
        hiddenFiveLayout.setVisibility(View.GONE);
        layoutTwo.setVisibility(View.GONE);
        layoutThree.setVisibility(View.GONE);
        layoutFour.setVisibility(View.VISIBLE);

        hiddenOneLabelTv.setText("开具文书人员：");
        hiddenOneTv.setText(CommonUtil.avoidNullString(safeHiddenProcessItemVo.getOperator_name()));

        labelOneTv.setText("开具时间：");
        nameOneTv.setText(CommonUtil.timeToStr(safeHiddenProcessItemVo.getCreate_time()));


        getAttachment(safeHiddenProcessItemVo.getId());
    }

    /**
     *
     */
    private void docPrintUpload() {

        if (UserTypeUtil.isGovType(AccountUtil.getUserType())) {
            if (SafeHiddenBo.Status.doc.getValue().equals(safeHiddenProcessItemVo.getType())) {
                if (SafeHiddenBo.Doc.site_inspection_doc.getValue().equals(safeHiddenProcessItemVo.getDocument_type())) {
                    /**
                     * 这个文书，政府人员不需要持有证书，即可打印和上传的文书
                     */
                    govWithoutCertificateDocUploadPicture();
                } else {
                    /**
                     * 其他文书，即使是政府人员，但必须是有证书的人，才可以打印和上传的文书
                     */
                    govWithCertificateDocUploadPicture();
                }
            }
        } else {
            /**
             * 企业人员，无权打印和上传文书
             */
            bottomLayout.setVisibility(View.GONE);
        }

    }

    /**
     * 无证上传图片判断
     */
    private void govWithoutCertificateDocUploadPicture() {


        if (attests != null && !attests.isEmpty()) {

            boolean show = true;

            for (SafeHiddenDangerFile files : attests) {
                if (files.getType().equals(SafeHiddenBo.Type.img.getValue())) {
                    show = false;
                    break;
                }
            }

            if (show) {
                uploadBtn.setVisibility(View.VISIBLE);
                viewLine.setVisibility(View.VISIBLE);

                uploadBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putSerializable(KeyConstants.KEY_SAFE_HIDDEN_PROCESS_ITEM_VO, safeHiddenProcessItemVo);
                        bundle.putString(KeyConstants.KEY_DOC_TYPE, safeHiddenProcessItemVo.getType());
                        UIHelper.showActivity(SafeHiddenProcessDetailActivity.this, bundle, SafeHiddenUploadDocumentPictureActivity.class);
                    }
                });
            } else {
                uploadBtn.setVisibility(View.GONE);
                viewLine.setVisibility(View.GONE);
            }
        }

        /**
         * 无证人员可以打印此类文书
         */
        printerBtn.setVisibility(View.VISIBLE);
        printerBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mHUDUtil.showHUD();
                if (!attests.isEmpty()) {
                    for (SafeHiddenDangerFile file : attests) {
                        if (file.getPath() != null && file.getPath().contains("pdf")) {
                            if (CheckAppExist.checkCanonPrinterExist(SafeHiddenProcessDetailActivity.this)) {
                                printFile(file.getPath(), "doc.pdf");
                            } else {
                                getPrinterApk();
                            }
                        }
                    }
                } else {
                    mHUDUtil.showErrorTip("无文书");
                }

            }
        });

    }

    /**
     * 有证政府人员上传图片判断
     */
    private void govWithCertificateDocUploadPicture() {

        if (attests != null && !attests.isEmpty()) {

            boolean show = true;

            for (SafeHiddenDangerFile files : attests) {
                if (files.getType().equals(SafeHiddenBo.Type.img.getValue())) {
                    show = false;
                    break;
                }
            }

            if (show && !(StringUtils.isEmpty(AccountUtil.getTypeId()) || "null".equalsIgnoreCase(AccountUtil.getTypeId()))) {

                uploadBtn.setVisibility(View.VISIBLE);
                viewLine.setVisibility(View.VISIBLE);

                uploadBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putSerializable(KeyConstants.KEY_SAFE_HIDDEN_PROCESS_ITEM_VO, safeHiddenProcessItemVo);
                        bundle.putString(KeyConstants.KEY_DOC_TYPE, safeHiddenProcessItemVo.getType());
                        UIHelper.showActivity(SafeHiddenProcessDetailActivity.this, bundle, SafeHiddenUploadDocumentPictureActivity.class);
                    }
                });
            } else {
                uploadBtn.setVisibility(View.GONE);
                viewLine.setVisibility(View.GONE);
            }
        }

        /**
         * 只有持证人员可以打印此类文书
         */
        if (!(StringUtils.isEmpty(AccountUtil.getTypeId()) || "null".equalsIgnoreCase(AccountUtil.getTypeId()))) {

            printerBtn.setVisibility(View.VISIBLE);
            printerBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    mHUDUtil.showHUD();

                    if (!attests.isEmpty()) {
                        for (SafeHiddenDangerFile file : attests) {
                            if (file.getPath() != null && file.getPath().contains("pdf")) {
                                if (CheckAppExist.checkCanonPrinterExist(SafeHiddenProcessDetailActivity.this)) {
                                    printFile(file.getPath(), "doc.pdf");
                                } else {
                                    getPrinterApk();
                                }
                            }
                        }
                    } else {
                        mHUDUtil.showErrorTip("无文书");
                    }

                }
            });

        }

    }

    /**
     * 获取附件
     */
    private void getAttachment(String id) {

        LemonRequestParams params = new LemonRequestParams("");
        params.put("record_id", id);

        SafeHiddenServices
                .init()
                .getHiddenAttachmentByOperation(params);
    }

    /**
     * 显示图片和音频详情
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMediaEvent(HiddenMediaNewEvent event) {

        if (SafeHiddenProcessDetailActivity.class.getName().equals(event.getTag())) {

            String url = event.getFiles().get(event.getPosition()).getPath();

            if (LemonFileHelper.isImageUrl(url)) {
                List<SafeHiddenDangerFile> files = event.getFiles();
                List<PhotoInfo> photos = new ArrayList<>();

                int j = 0;
                int currentItem = 0;
                for (int i = 0; i < files.size(); i++) {
                    if (LemonFileHelper.isImageUrl(files.get(i).getPath())) {

                        if (url.equals(files.get(i).getPath())) {
                            currentItem = j;
                        }

                        PhotoInfo photoInfo = new PhotoInfo();
                        photoInfo.setPhotoId(j);
                        photoInfo.setPhotoPath(UrlFormatUtils.formatFiles(files.get(i).getPath()));
                        photos.add(photoInfo);
                        j++;
                    }
                }

                if (photos != null && photos.size() != 0) {
                    UIHelper.showPhotoView(this, photos, currentItem);
                }
            } else if (LemonFileHelper.isVoiceUrl(url)) {
                playVoice(UrlFormatUtils.formatFiles(url));
            }

        }
    }

    /**
     * 附件
     */
    private SafeHiddenAttachmentFileVoAdapter safeHiddenAttachmentFileVoAdapter;
    private List<SafeHiddenDangerFile> attests;

    private void initRecyclerView() {
        attests = new ArrayList<>();
        GridLayoutManager gridLayoutManager = new GridLayoutManager(SafeHiddenProcessDetailActivity.this, 3);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setNestedScrollingEnabled(false);
        safeHiddenAttachmentFileVoAdapter = new SafeHiddenAttachmentFileVoAdapter(attests, SafeHiddenProcessDetailActivity.class.getName());
        recyclerView.setAdapter(safeHiddenAttachmentFileVoAdapter);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(HttpCallbackEvent event) {
        if (KeyConstants.URL_GET_SAFE_HIDDEN_ATTACHMENT_BY_ID.equals(event.getTag())) {                    //获取附件
            if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {
                mHUDUtil.showHUD();
            } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow()) {
                mHUDUtil.hidden();
                if (Constants.Result.SUCCESS == event.getEventResult()) {

                    if (safeHiddenAttachmentFileVoAdapter != null) {
                        attests.clear();
                        safeHiddenAttachmentFileVoAdapter.notifyDataSetChanged();
                        safeHiddenAttachmentFileVoAdapter.addItems((List<SafeHiddenDangerFile>) event.getObj());

                        docPrintUpload();
                    }

                } else if (Constants.Result.ERROR == event.getEventResult()) {

                    mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {

                        }
                    });

                }
            }
        }
    }

    /**
     * 打印文书
     */
    private void printFile(String fileUrl, String fileName) {
        OkHttpUtils
                .get()
                .url(UrlFormatUtils.formatFiles(fileUrl))
                .build()
                .execute(new FileCallBack(FileUtil.getAppDocTempDir(SafeHiddenProcessDetailActivity.this), fileName) {

                    @Override
                    public void onError(Call call, Exception e) {
                        mHUDUtil.showErrorTip("获取文件失败。");
                    }

                    @Override
                    public void onResponse(File response) {
                        mHUDUtil.hidden();
                        callPrinter(response);
                    }

                    @Override
                    public void inProgress(float progress, long total) {

                    }
                });
    }

}
